<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="部门" prop="deptAbbreviation">
        <el-select v-model="queryParams.deptAbbreviation" placeholder="请选择部门" clearable>
          <el-option
              v-for="dict in dict.type.dept_abbreviation"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="请输入标题"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分析时间">
        <el-date-picker
            v-model="dateRangeAnalysisDate"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['quality:analysis:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['quality:analysis:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['quality:analysis:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['quality:analysis:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-view"
          size="mini"
          @click="handleTopPreview"
          v-hasPermi="['quality:analysis:export']"
        >Top问题</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
        v-loading="loading"
        :data="analysisList"
        @row-click="handlePreview"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分析id" align="center" prop="id" v-if="true"/>
      <el-table-column label="部门" align="center" prop="deptAbbreviation">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dept_abbreviation" :value="scope.row.deptAbbreviation"/>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" width="240"/>
      <el-table-column label="月份" align="center" prop="analysisMonth">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.analysisMonth, '{y}-{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门讲评" align="center" prop="deptCommentary" />
      <el-table-column label="班组讲评" align="center" prop="groupCommentary" />
      <el-table-column label="分析时间" align="center" prop="analysisDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.analysisDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click.stop="handlePreview(scope.row)"
              v-hasPermi="['quality:physicalReport:edit']"
          >预览</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click.stop="handleUpdate(scope.row)"
              v-hasPermi="['quality:analysis:edit']"
          >修改</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click.stop="handleDelete(scope.row)"
              v-hasPermi="['quality:analysis:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改实物质量分析对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="75%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="部门" prop="deptAbbreviation">
              <el-select v-model="form.deptAbbreviation" placeholder="请选择部门">
                <el-option
                    v-for="dict in dict.type.dept_abbreviation"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="月份" prop="analysisMonth">
              <el-date-picker clearable
                              v-model="form.analysisMonth"
                              type="month"
                              @change="formDateRange"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择月份">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分析时间" prop="analysisDate">
              <el-date-picker clearable
                              v-model="form.analysisDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择分析时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="部门讲评" prop="deptCommentary">
              <el-input v-model="form.deptCommentary" placeholder="请输入部门讲评" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="班组讲评" prop="groupCommentary">
              <el-input v-model="form.groupCommentary" placeholder="请输入班组讲评" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table v-loading="loading" :data="reportList" v-if="show" size="large">
        <el-table-column label="通报id" align="center" prop="reportId" width="96"/>
        <el-table-column label="编号" align="center" prop="reportNumber" />
        <el-table-column label="名称" align="center" prop="reportName" width="240">
          <template #default="scope">
            <dict-tag :options="dict.type.report_class" :value="scope.row.reportName"/>
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" prop="deptAbbreviation">
          <template #default="scope">
            <dict-tag :options="dict.type.dept_abbreviation" :value="scope.row.deptAbbreviation"/>
          </template>
        </el-table-column>
        <el-table-column label="日期" align="center" sortable prop="reportDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.reportDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <div>
      <analysis-preview
          :visible.sync="preview"
          :form="form"
      />
    </div>

    <div>
      <el-dialog
        :visible.sync="topPreview"
        title="Top预览"
        width="900px"
        append-to-body
        destroy-on-close
      >
      <top-preview
          :topPreviewList="topPreviewList"
      />
      </el-dialog>
    </div>

  </div>
</template>

<script>
import {
  listAnalysis,
  getAnalysis,
  delAnalysis,
  addAnalysis,
  updateAnalysis,
  getTopPreview
} from "@/api/quality/analysis";
import { getThisMonthRange } from "@/utils/dateRange";
import { listPhysicalReport } from '@/api/quality/physicalReport'
import { getInfo } from '@/api/login';
import { positiveIntNum1, required } from '@/utils/rules'
import AnalysisPreview from '@/views/quality/common/AnalysisPreview.vue'
import { parseTime } from '@/utils/ruoyi'
import TopPreview from "@/views/quality/common/TopPreview.vue";
export default {
  name: "Analysis",
  components: {TopPreview, AnalysisPreview },
  dicts: ['dept_abbreviation', 'dept_fullname', 'report_class'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实物质量分析表格数据
      analysisList: [],
      // 实物质量通报表格数据
      reportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示通报列表
      show: false,
      //通报预览开关
      preview:false,
      //top问题预览开关
      topPreview:false,
      //top问题列表
      topPreviewList:[],
      // 分析时间时间范围
      dateRangeAnalysisDate: [],
      // 通报时间时间范围
      dateRangeReportDate: [],
      //当前用户
      user:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptAbbreviation: undefined,
        title: undefined,
        analysisMonth: undefined,
        analysisDate: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [required],
        deptAbbreviation: [required],
        title:[required],
        deptCommentary: [required,positiveIntNum1],
        groupCommentary:[required,positiveIntNum1],
        analysisMonth:[required],
        analysisDate: [required],
      }
    };
  },
  created() {
    this.getList();
    this.getUser();
  },
  methods: {
    /** 查询实物质量分析列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.dateRangeAnalysisDate && '' !== this.dateRangeAnalysisDate) {
        this.queryParams.params["beginAnalysisDate"] = this.dateRangeAnalysisDate[0];
        this.queryParams.params["endAnalysisDate"] = this.dateRangeAnalysisDate[1];
      }
      listAnalysis(this.queryParams).then(response => {
        this.analysisList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.show = false;
      this.queryParams.deptAbbreviation = null;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        deptAbbreviation: undefined,
        title: undefined,
        deptCommentary: undefined,
        groupCommentary: undefined,
        analysisMonth: undefined,
        technologyReportNumber: undefined,
        technologyDefectNumber: undefined,
        technologyDefectFine: undefined,
        physicalReportNumber: undefined,
        physicalDefectNumber: undefined,
        physicalDefectFine: undefined,
        defectTotal: undefined,
        listNumber: undefined,
        listDefect: undefined,
        analysisDate: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
      this.topPreview = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeAnalysisDate = [];
      this.dateRangeReportDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.show = true;
      this.title = "添加实物质量分析";
      const date = new Date()
      this.form.analysisDate = date;
      this.form.deptAbbreviation = this.user.deptId.toString();
      this.dateRangeReportDate = getThisMonthRange(date);
      this.form.title = "实物质量自主管理分析报告";
      // this.form.analysisMonth = parseTime(date,'{y}-{m}-{d} {h}:{i}:{s}');
      this.getReportList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getAnalysis(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.show = true;
        this.title = "修改实物质量分析";
        const date = new Date(Date.parse(this.form.analysisMonth));
        this.dateRangeReportDate = getThisMonthRange(date);
        this.getReportList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.form.params = {};
        if (null != this.dateRangeReportDate && '' !== this.dateRangeReportDate) {
          this.form.params["beginReportDate"] = this.dateRangeReportDate[0];
          this.form.params["endReportDate"] = this.dateRangeReportDate[1];
        }
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateAnalysis(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.show = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addAnalysis(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除实物质量分析编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delAnalysis(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('quality/analysis/export', {
        ...this.queryParams
      }, `自主管理情况汇总表_${new Date().getTime()}.xlsx`)
    },

    /** 获取质量通报列表操作 */
    getReportList(){
      this.queryParams.deptAbbreviation = this.form.deptAbbreviation;
      this.queryParams.params = {};
      if (null != this.dateRangeReportDate && '' !== this.dateRangeReportDate) {
        this.queryParams.params["beginReportDate"] = this.dateRangeReportDate[0];
        this.queryParams.params["endReportDate"] = this.dateRangeReportDate[1];
      }
      listPhysicalReport(this.queryParams).then(response => {
        this.reportList = response.rows;
        this.show = true;
      });
    },

    //日期改变时触发
    formDateRange(value){
      const date = new Date(Date.parse(this.form.analysisMonth));
      this.dateRangeReportDate = getThisMonthRange(date);
      this.form.beginReportDate = this.dateRangeReportDate[0];
      this.form.endReportDate = this.dateRangeReportDate[1];
      this.getReportList();
    },

    /** 获取当前用户信息 */
    getUser(){
      getInfo().then(res=>{
        //获取用户信息
        this.user = res.data.user;
      });
    },

    /** 点击列表预览通报内容*/
    handlePreview(row){
      this.reset();
      const id = row.id || this.ids;
      getAnalysis(id).then(response => {
        this.form = response.data;
        const deptAbbreviation = Number(this.form.deptAbbreviation);
        this.form.fullName = this.selectDictLabel(this.dict.type.dept_fullname, deptAbbreviation);
        this.form.deptAbb = this.selectDictLabel(this.dict.type.dept_abbreviation, deptAbbreviation);
        this.form.month = parseTime(this.form.analysisMonth, '{y}年{m}月');
        this.form.date = parseTime(this.form.analysisDate, '{y}年{m}月{d}日');
        this.preview = true;
      });
    },

    /** 点击列表预览Top问题内容*/
    handleTopPreview(row) {
      const ids = row.id || this.ids;
      getTopPreview(ids).then( res => {
        this.topPreviewList = res.data;
        this.topPreview = true;
      })
    }
  }
};
</script>
